﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//
using CommonClass;
using EncryptProject;
using CommonBase;
using SurveillanceLib;


namespace MatrixManagement
{
    /// <summary>
    /// 设备管理界面
    /// </summary>
    public partial class frm_DataBase : Form
    {
        #region 变量

        Action refreshTreeAction;
        SurveillanceDAL dataOperation = new SurveillanceDAL();
        DataGridViewRow selectedDriver; // 列表中所选择的设备
        List<ArgModel> driverTypesList; // 查询 记录所有设备类型
        bool isNew; // 是否是新增设备，true: 新增设备 | false: 修改设备

        #endregion

        #region 方法

        #region Driver 操作
        /// <summary>
        /// 新增设备
        /// </summary>
        private void addDriver()
        {
            try
            {
                int resultCount = dataOperation.AddTreeNodeItem(txtTreeText.Text.Trim(),
                    txtTreeName.Text.Trim(), txtDriverName.Text.Trim(),
                    EncryptAlgorithmHelper.Encrypt2(txtDriverPwd.Text.Trim(), Utilities.MachineCode), 
                    txtDriverPort.Text.Trim(), txtExptChannelNo.Text.Trim(), 
                    ckStatus.Checked ? 1 : 0, cbType.SelectedValue.ToString());

                if (resultCount > 0)
                {
                    MessageBox.Show("数据新增成功！", ConstantString.MSG_COMPANY);
                    initializeTable(); // 重新加载表格
                    
                    // 选择并显示最新加的设备信息
                    if (dGViewDriver.Rows != null && dGViewDriver.Rows.Count > 0)
                    {
                        selectedDriver = dGViewDriver.Rows[0]; // 默认选中第一行
                        showTreeNodeDetail(); // 详细显示
                    }

                    if (this.refreshTreeAction != null)
                        this.refreshTreeAction();
                }
                else
                    MessageBox.Show("数据新增失败！", ConstantString.MSG_COMPANY);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
        }

        /// <summary>
        /// 修改设备
        /// </summary>
        private void editDriver()
        {
            try
            {
                int resultCount = dataOperation.EditTreeNodeItem(selectedDriver.Cells["columnID"].Value.ToString(),
                    txtTreeText.Text.Trim(), txtTreeName.Text.Trim(), txtDriverName.Text.Trim(),
                    EncryptAlgorithmHelper.Encrypt2(txtDriverPwd.Text.Trim(), Utilities.MachineCode),
                    txtDriverPort.Text.Trim(), txtExptChannelNo.Text.Trim(),
                    ckStatus.Checked ? 1 : 0, cbType.SelectedValue.ToString());

                if (resultCount > 0)
                {
                    MessageBox.Show("数据修改成功！", ConstantString.MSG_COMPANY);
                    int selectedIndex = selectedDriver.Index; // 记录所选序号
                    initializeTable(); // 重新加载表格

                    // 选择并显示修改的设备信息
                    selectedDriver = dGViewDriver.Rows[selectedIndex];
                    showTreeNodeDetail(); // 详细显示
                    dGViewDriver.Rows[selectedIndex].Selected = true; // 默认选中该行

                    if (this.refreshTreeAction != null)
                        this.refreshTreeAction();
                }
                else
                    MessageBox.Show("数据修改失败！", ConstantString.MSG_COMPANY);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
        }

        /// <summary>
        /// 删除设备
        /// </summary>
        private void deleteDriver()
        {
            if (dataOperation.DeleteTreeNodeItem(selectedDriver.Cells["columnID"].Value.ToString()) > 0)
            {
                MessageBox.Show("数据删除成功！", ConstantString.MSG_COMPANY);
                initializeTable(); // 重新加载表格

                // 选择并显示第一个设备信息
                if (dGViewDriver.Rows != null && dGViewDriver.Rows.Count > 0)
                {
                    selectedDriver = dGViewDriver.Rows[0]; // 默认选中第一行
                    showTreeNodeDetail(); // 详细显示
                }

                if (this.refreshTreeAction != null)
                    this.refreshTreeAction();
            }
            else
                MessageBox.Show("数据删除失败！", ConstantString.MSG_COMPANY);
        }
        #endregion

        #region 验证
        /// <summary>
        /// 检查 TextBox 的 Text 属性是否为空或没有字符值
        /// </summary>
        /// <param name="sender">进行检查的 TextBox 控件</param>
        /// <param name="errorMessage">错误提示信息</param>
        /// <returns></returns>
        private bool validateTextBoxValue(TextBox sender, string errorMessage)
        {
            if (!string.IsNullOrWhiteSpace(sender.Text))
                return true;
            else
            {
                MessageBox.Show(errorMessage, ConstantString.MSG_COMPANY);
                sender.Focus();

                return false;
            }
        }

        /// <summary>
        /// 检查两次密码是否一致
        /// </summary>
        /// <param name="pwdSender">修改密码</param>
        /// <param name="confirmPwdSender">确认密码</param>
        /// <param name="errorMessage">错误提示信息</param>
        /// <returns></returns>
        private bool validatePassword(TextBox pwdSender, TextBox confirmPwdSender, string errorMessage)
        {
            if (!pwdSender.Text.Equals(confirmPwdSender.Text))
            {
                MessageBox.Show(errorMessage, ConstantString.MSG_COMPANY);
                confirmPwdSender.Text = string.Empty;
                confirmPwdSender.Focus();

                return false;
            }

            return true;
        }

        /// <summary>
        /// 检查是否已存在该设备
        /// </summary>
        /// <param name="treeName">设备 IP</param>
        /// <param name="driverPort">设备端口号</param>
        /// <param name="errorMessage">错误提示信息</param>
        /// <returns></returns>
        private bool validateExistDriver(string treeName, string driverPort, string errorMessage)
        {
            if (!isNew && selectedDriver != null && 
                !string.IsNullOrWhiteSpace(txtTreeName.Text) &&
                !string.IsNullOrWhiteSpace(txtDriverPort.Text) &&
                txtTreeName.Text.Equals(selectedDriver.Cells["columnIP"].Value.ToString()) &&
                txtDriverPort.Text.Equals(selectedDriver.Cells["columnPort"].Value.ToString())) // 修改情况时，并且没有修改 treeName 与 driverPort
            {
                return true;
            }

            // 新建情况 | 修改了 treeName 与 driverPort 时
            if (dGViewDriver.DataSource != null && dGViewDriver.DataSource is DataTable &&
                (dGViewDriver.DataSource as DataTable).Rows != null &&
                (dGViewDriver.DataSource as DataTable).Rows.Count > 0)
            {
                foreach (DataRow row in (dGViewDriver.DataSource as DataTable).Rows)
                {
                    if (row["TreeName"].ToString().Equals(treeName) &&
                        row["DriverPort"].ToString().Equals(driverPort))
                    {
                        MessageBox.Show(errorMessage, ConstantString.MSG_COMPANY);
                        return false;
                    }
                }
            }

            return true;
        }
        #endregion

        /// <summary>
        /// 还原为默认值
        /// </summary>
        private void clearValue2Default()
        {
            cbType.SelectedIndex = 0;
            ckStatus.Checked = true;
            txtTreeText.Text = txtTreeName.Text = txtDriverPort.Text = txtExptChannelNo.Text = txtDriverName.Text =
                txtDriverPwd.Text = txtDriverPwd2.Text = string.Empty;
        }

        /// <summary>
        /// 修改布局控件状态
        /// </summary>
        /// <param name="canSelectTable">是否可选择表格</param>
        /// <param name="groupName">组名称</param>
        /// <param name="isAdd">是否为新增</param>
        private void changeLayoutState(bool canSelectTable, string groupName, bool isAdd)
        {
            btnAdd.Enabled = btnEdit.Enabled = btnDelete.Enabled = dGViewDriver.Enabled = canSelectTable;

            gbInfo.Text = groupName;
            gbInfo.Enabled = !canSelectTable;

            isNew = isAdd;
        }

        /// <summary>
        /// 显示详细信息
        /// </summary>
        private void showTreeNodeDetail()
        {
            if (selectedDriver != null)
            {
                txtTreeText.Text = selectedDriver.Cells["columnName"].Value.ToString();
                txtTreeName.Text = selectedDriver.Cells["columnIP"].Value.ToString();
                txtDriverPort.Text = selectedDriver.Cells["columnPort"].Value.ToString();
                cbType.SelectedValue = getKeyThroughValue(selectedDriver.Cells["columnType"].Value.ToString());
                txtExptChannelNo.Text = selectedDriver.Cells["columnExptChannel"].Value.ToString();
                ckStatus.Checked = selectedDriver.Cells["columnStatus"].Value.ToString().Equals("启用");
                txtDriverName.Text = selectedDriver.Cells["columnUserName"].Value.ToString();
                txtDriverPwd.Text = txtDriverPwd2.Text = string.Empty;
            }
        }

        /// <summary>
        /// 初始化表格
        /// </summary>
        private void initializeTable()
        {
            DataSet dsTreeNode = dataOperation.GetDataSet(SurveillanceDAL.QUERY_GET_TREENODEDATA,
                string.Empty, "db_VWMSConnectionString", string.Format("{0}.exe", Application.ProductName));
            if (dsTreeNode == null)
                return;

            dGViewDriver.AutoGenerateColumns = false;
            dGViewDriver.DataSource = dsTreeNode.Tables[0];

            if(dsTreeNode.Tables[0] != null &&
                dsTreeNode.Tables[0].Rows.Count > 0)
            {
                btnEdit.Enabled = btnDelete.Enabled = true;
            }
            else
            {
                btnEdit.Enabled = btnDelete.Enabled = false;
            }
        }

        /// <summary>
        /// 填充设备类型下拉值
        /// </summary>
        private void fillDriverTypeList()
        {
            ArgModel argType;
            driverTypesList = new List<ArgModel>();

            // 填充 DriverTypeEnum 枚举
            foreach (DriverTypeEnum driverType in Utilities.GetEnumValues<DriverTypeEnum>())
            {
                argType = new ArgModel()
                {
                    sKey = driverType.ToString(),
                    sValue = Utilities.GetEnumDisplayDescription(driverType),
                };
                driverTypesList.Add(argType);
            }

            cbType.DataSource = driverTypesList;
        }

        /// <summary>
        /// 通过 value 值获取 key 值
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private string getKeyThroughValue(string value)
        {
            if (driverTypesList != null && driverTypesList.Count > 0)
            {
                foreach (ArgModel arg in driverTypesList)
                {
                    if (arg.sValue.Equals(value))
                        return arg.sKey;
                }
            }

            return string.Empty;
        }

        #endregion

        #region 构造函数

        /// <summary>
        /// 
        /// </summary>
        /// <param name="refreshTree">刷新主界面中的树</param>
        public frm_DataBase(Action refreshTree)
        {
            InitializeComponent();

            this.refreshTreeAction = refreshTree;
            initializeTable(); // 加载表格
            fillDriverTypeList(); // 填充设备类型值
        }

        #endregion

        #region 事件

        /// <summary>
        /// 选择列表信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dGViewDriver_SelectionChanged(object sender, EventArgs e)
        {
            DataGridView view = sender as DataGridView;
            if (view.SelectedRows != null && view.SelectedRows.Count == 1) // 单选
            {
                selectedDriver = view.SelectedRows[0];
                showTreeNodeDetail(); // 详细显示
            }
        }

        /// <summary>
        /// 新增设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            changeLayoutState(false, "新增设备", true); // 新增
            clearValue2Default(); // 清空值
        }

        /// <summary>
        /// 修改设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (selectedDriver == null)
            {
                MessageBox.Show("请选择需要修改的设备", ConstantString.MSG_COMPANY);
                return;
            }

            changeLayoutState(false, "修改设备", false); // 修改
        }

        /// <summary>
        /// 删除设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (selectedDriver == null)
            {
                MessageBox.Show("请选择需要删除的设备", ConstantString.MSG_COMPANY);
                return;
            }

            if (MessageBox.Show("确定要删除设备吗？", ConstantString.MSG_COMPANY, MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question, MessageBoxDefaultButton.Button1,
                    MessageBoxOptions.DefaultDesktopOnly) == DialogResult.Yes)
            {
                deleteDriver(); // 删除
            }
        }


        /// <summary>
        /// 确定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnApply_Click(object sender, EventArgs e)
        {
            if (validateTextBoxValue(txtTreeName, "请输入设备 IP 地址") &&
                validateTextBoxValue(txtDriverPort, "请输入设备端口号") &&
                validateTextBoxValue(txtDriverName, "请输入用户名") &&
                validateTextBoxValue(txtDriverPwd, "请输入密码") &&
                validatePassword(txtDriverPwd, txtDriverPwd2, "两次输入的密码不一致") &&
                validateExistDriver(txtTreeName.Text.Trim(), txtDriverPort.Text.Trim(), "该设备已经存在"))
            {
                if (isNew) // 新增
                {
                    addDriver();
                }
                else // 修改
                {
                    editDriver();
                }

                changeLayoutState(true, "详细信息", false); // 修改
            }
        }

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            showTreeNodeDetail(); // 详细显示
            changeLayoutState(true, "详细信息", false); // 修改
        }

        #endregion
    }
}
